// 8. Add this to the top of history.js
var CurrentUser; // Global variable

// 7. Copy the getName() function and call from main.js
function getName() {
    var user = JSON.parse(localStorage.getItem("loggedinUser"));
    if (user) {
        console.log("Currently logged in:  " + user["name"]);
        document.getElementById("name-goes-here").innerText = user["name"];

        // 9. Add this after we get the logged in user from local storage
        CurrentUser = user; // Added to set current user in global var
    } else {
        console.log("No one is logged in");
    }
}
getName(); // run the function

// 11. Open history.js and create a new function to populate History.
function populateHistory() {
    // 12. In the function lets get the loggedInUser, the users and the email from the loggedinUser.
    // find out who is logged in 
    var loggedinUser = JSON.parse(localStorage.getItem("loggedinUser")); // person who is logged in
    var users = JSON.parse(localStorage.getItem("users")); // the whole users database
    if (!loggedinUser || !users) {
        console.log("No user is logged in or user data is missing.");
        return;
    }
    let email = loggedinUser["email"];

    // 13. We get the user using the loggedInUser’s email then we get the user’s history.
    const user = users.find(u => u.email === email);
    let historyArray = [];
    if (user) {
        historyArray = user["history"];
    } else {
        console.log("No one is logged in");
    }

    // 14. We create a loop that goes through each of the history items in the user’s history array. 
    // We also get the card template and the card location.
    historyArray.forEach((hist) => {
        // Get references to the HTML card and div to hold the history
        let historyCardTemplate = document.getElementById("simple-history-card");
        let historyCardGroup = document.getElementById("history-goes-here");

        // 15. We use cloneNode to create a copy of the card template.
        let onecard = historyCardTemplate.content.cloneNode(true);

        // 16. Get the date from the history item and put it in the ‘info’ part of the history card. 
        // Finally, we add the card to the end of the history div.
        let d = hist.date;
        onecard.querySelector(".info").innerHTML = d;
        historyCardGroup.appendChild(onecard);
    });
}
populateHistory();